#include "DoubleLinkList.h"
#include <iostream>

DoubleLinkList::DoubleLinkList():head(new Node),size(0)
{
    head->data = 0; 
    head->next = head->prev = nullptr;
}

DoubleLinkList::~DoubleLinkList()//因为指针在节点里面，所以和单链表一样
{
    while(head != nullptr)
    {
        Node * nextNode = head->next;//记下下一个节点
        delete head;//释放现在节点
        head = nextNode;//把下一个变成现在的
    }
}

//尾插
void DoubleLinkList::InsertTail(ElementType element)
{
    Node *newNode = CreatNode(element);
    Node *end = GetEnd();
    end->next = newNode;
    newNode->prev = end; 
    size++;
}

//前插
void DoubleLinkList::InsertHead(ElementType element)
{
    Node *newNode = CreatNode(element);//创节点
    newNode->next = head->next;
    newNode->prev = head;
    if(size > 0)
    {
        head->next->prev = newNode;//当心！head的next为空则不成立
    }
    head->next = newNode;
    size++;
}

//遍历
void DoubleLinkList::show()//与单链相同
{
    Node * travelPoint = head;
    while(travelPoint->next != nullptr)//头节点不放有效数据
    {
        std::cout<<travelPoint->next->data<<" ";
        travelPoint = travelPoint->next;//继续访问下一个节点
    }
    std::cout<<std::endl;
}

//反向遍历
void DoubleLinkList::ReserveShow()
{
    Node *end = GetEnd();
    while(end != head)
    {
        std::cout<<end->data<<" ";
        end = end->prev;//打印数值之后往前走一个
    }
    std::cout<<std::endl;
}

//双链的逆序
void DoubleLinkList::Reserve()
{
    Node * travelPoint = head->next;
    std::swap(travelPoint->prev,travelPoint->next);
    travelPoint->next = nullptr;
    while(travelPoint->prev != nullptr)     
    {
        travelPoint = travelPoint->prev;
        std::swap(travelPoint->prev,travelPoint->next);
    }
    head->next = travelPoint;
    travelPoint->prev = head;
}





DoubleLinkList:: Node *DoubleLinkList::GetEnd()
{
    Node *travelPoint = head;
    while(travelPoint->next != nullptr)
    {
        travelPoint = travelPoint->next;
    }
    return travelPoint;
}

DoubleLinkList::Node *DoubleLinkList::CreatNode(ElementType element)
{
    Node *newNode = new Node;
    newNode->data = element;
    newNode->next = newNode->prev = nullptr;
    return newNode;
}
